package com.reload;

import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;
import reactor.netty.http.server.HttpServer;

import java.io.IOException;

/**
 * @Date: 2024/4/28 下午4:22
 * @Version: 17
 * @Author: Reloading
 * @Description: WebFlux原生写法
 */
public class OriginalFlux {
    public static void main(String[] args) throws IOException {
        HttpHandler httpHandler = (ServerHttpRequest request, ServerHttpResponse response) -> {
            // 编写请求处理的业务
            System.out.println("请求进来了：" + request.getURI());
            // 获取响应头
            response.getHeaders();
            // 获取cookies
            response.getCookies();
            // 获取响应状态码
            response.getStatusCode();
            // buffer工厂 创建响应数据的DataBuffer
            DataBufferFactory dataBufferFactory = response.bufferFactory();
            DataBuffer wrap = dataBufferFactory.wrap((request.getURI().toString() + " ==> Hello").getBytes());
            // 把XXX写出去  参数：数据的发布者
            // 处理完成的信号
            return response.writeWith(Mono.just(wrap));
        };

        // 启动一个服务器监听8080端口,接受数据,拿到数据交给HttpHandler 进行请求处理
        ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);

        // 启动Netty服务器
        HttpServer.create()
                .host("localhost")
                .port(8080)
                .handle(adapter)
                // 现在就绑定
                .bindNow();
        System.out.println("服务器启动完成....监听8080,接受请求");
        System.in.read();
        System.out.println("服务器停止");

    }
}
